#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
中介者模式 (Mediator Pattern) - Python实现详解

中介者模式是一种行为设计模式，它定义了一系列对象之间的交互方式，
使原本直接交互的对象通过中介者进行交互，从而降低对象之间的耦合度。

与Java对比：
1. Python的动态特性使得中介者更加灵活
2. Python支持函数式编程，可以使用函数作为中介者
3. Python的装饰器可以简化中介者的实现
4. Python的异步特性适合实现异步中介者

作者: Assistant
日期: 2024
"""

import asyncio
import threading
import time
from abc import ABC, abstractmethod
from typing import Any, Dict, List, Optional, Callable, Set
from dataclasses import dataclass
from enum import Enum
import weakref
from collections import defaultdict
import json


# ============================================================================
# 1. 传统中介者模式实现
# ============================================================================

class Mediator(ABC):
    """
    中介者抽象类
    定义同事对象之间的交互接口
    """
    
    @abstractmethod
    def notify(self, sender: 'Colleague', event: str, data: Any = None) -> None:
        """处理同事对象发送的通知"""
        pass


class Colleague(ABC):
    """
    同事类抽象基类
    所有需要通过中介者交互的对象都应该继承此类
    """
    
    def __init__(self, mediator: Mediator = None):
        self._mediator = mediator
    
    def set_mediator(self, mediator: Mediator) -> None:
        """设置中介者"""
        self._mediator = mediator
    
    def notify_mediator(self, event: str, data: Any = None) -> None:
        """向中介者发送通知"""
        if self._mediator:
            self._mediator.notify(self, event, data)


# 具体同事类示例：聊天室用户
class ChatUser(Colleague):
    """
    聊天用户类
    """
    
    def __init__(self, name: str, mediator: Mediator = None):
        super().__init__(mediator)
        self.name = name
        self.messages: List[str] = []
    
    def send_message(self, message: str, target: str = None) -> None:
        """发送消息"""
        print(f"{self.name} 发送消息: {message}")
        self.notify_mediator('send_message', {
            'message': message,
            'target': target,
            'sender': self.name
        })
    
    def receive_message(self, message: str, sender: str) -> None:
        """接收消息"""
        formatted_message = f"[{sender}]: {message}"
        self.messages.append(formatted_message)
        print(f"{self.name} 收到消息: {formatted_message}")
    
    def join_room(self, room: str) -> None:
        """加入房间"""
        print(f"{self.name} 加入房间: {room}")
        self.notify_mediator('join_room', {'room': room, 'user': self.name})
    
    def leave_room(self, room: str) -> None:
        """离开房间"""
        print(f"{self.name} 离开房间: {room}")
        self.notify_mediator('leave_room', {'room': room, 'user': self.name})
    
    def get_message_history(self) -> List[str]:
        """获取消息历史"""
        return self.messages.copy()
    
    def __str__(self) -> str:
        return f"ChatUser({self.name})"


class ChatRoom(Mediator):
    """
    聊天室中介者
    管理用户之间的消息传递
    """
    
    def __init__(self, name: str):
        self.name = name
        self.users: Dict[str, ChatUser] = {}
        self.rooms: Dict[str, Set[str]] = defaultdict(set)
        self.message_history: List[Dict] = []
    
    def add_user(self, user: ChatUser) -> None:
        """添加用户"""
        self.users[user.name] = user
        user.set_mediator(self)
        print(f"聊天室 {self.name}: 用户 {user.name} 已加入")
    
    def remove_user(self, user_name: str) -> None:
        """移除用户"""
        if user_name in self.users:
            user = self.users[user_name]
            # 从所有房间中移除
            for room_users in self.rooms.values():
                room_users.discard(user_name)
            del self.users[user_name]
            user.set_mediator(None)
            print(f"聊天室 {self.name}: 用户 {user_name} 已离开")
    
    def notify(self, sender: Colleague, event: str, data: Any = None) -> None:
        """处理用户通知"""
        if not isinstance(sender, ChatUser):
            return
        
        if event == 'send_message':
            self._handle_message(sender, data)
        elif event == 'join_room':
            self._handle_join_room(sender, data)
        elif event == 'leave_room':
            self._handle_leave_room(sender, data)
    
    def _handle_message(self, sender: ChatUser, data: Dict) -> None:
        """处理消息发送"""
        message = data['message']
        target = data.get('target')
        
        # 记录消息历史
        self.message_history.append({
            'timestamp': time.time(),
            'sender': sender.name,
            'message': message,
            'target': target
        })
        
        if target:
            # 私聊消息
            if target in self.users:
                self.users[target].receive_message(message, sender.name)
            else:
                sender.receive_message(f"用户 {target} 不在线", "系统")
        else:
            # 广播消息给所有用户
            for user_name, user in self.users.items():
                if user_name != sender.name:
                    user.receive_message(message, sender.name)
    
    def _handle_join_room(self, sender: ChatUser, data: Dict) -> None:
        """处理加入房间"""
        room = data['room']
        self.rooms[room].add(sender.name)
        
        # 通知房间内其他用户
        for user_name in self.rooms[room]:
            if user_name != sender.name and user_name in self.users:
                self.users[user_name].receive_message(
                    f"{sender.name} 加入了房间 {room}", "系统"
                )
    
    def _handle_leave_room(self, sender: ChatUser, data: Dict) -> None:
        """处理离开房间"""
        room = data['room']
        self.rooms[room].discard(sender.name)
        
        # 通知房间内其他用户
        for user_name in self.rooms[room]:
            if user_name in self.users:
                self.users[user_name].receive_message(
                    f"{sender.name} 离开了房间 {room}", "系统"
                )
    
    def broadcast_to_room(self, room: str, message: str, sender: str = "系统") -> None:
        """向房间广播消息"""
        if room in self.rooms:
            for user_name in self.rooms[room]:
                if user_name in self.users:
                    self.users[user_name].receive_message(message, sender)
    
    def get_room_users(self, room: str) -> List[str]:
        """获取房间用户列表"""
        return list(self.rooms.get(room, set()))
    
    def get_online_users(self) -> List[str]:
        """获取在线用户列表"""
        return list(self.users.keys())
    
    def get_message_history(self, limit: int = 10) -> List[Dict]:
        """获取消息历史"""
        return self.message_history[-limit:]


# ============================================================================
# 2. 事件驱动的中介者模式
# ============================================================================

class EventType(Enum):
    """事件类型枚举"""
    USER_LOGIN = "user_login"
    USER_LOGOUT = "user_logout"
    MESSAGE_SENT = "message_sent"
    FILE_UPLOADED = "file_uploaded"
    SYSTEM_NOTIFICATION = "system_notification"


@dataclass
class Event:
    """事件数据类"""
    type: EventType
    source: str
    data: Dict[str, Any]
    timestamp: float = None
    
    def __post_init__(self):
        if self.timestamp is None:
            self.timestamp = time.time()


class EventMediator:
    """
    事件驱动的中介者
    使用发布-订阅模式管理事件
    """
    
    def __init__(self):
        self._subscribers: Dict[EventType, List[Callable]] = defaultdict(list)
        self._event_history: List[Event] = []
        self._max_history = 1000
        self._lock = threading.Lock()
    
    def subscribe(self, event_type: EventType, handler: Callable[[Event], None]) -> None:
        """订阅事件"""
        with self._lock:
            self._subscribers[event_type].append(handler)
            print(f"事件中介者: 订阅事件 {event_type.value}")
    
    def unsubscribe(self, event_type: EventType, handler: Callable[[Event], None]) -> None:
        """取消订阅事件"""
        with self._lock:
            if handler in self._subscribers[event_type]:
                self._subscribers[event_type].remove(handler)
                print(f"事件中介者: 取消订阅事件 {event_type.value}")
    
    def publish(self, event: Event) -> None:
        """发布事件"""
        with self._lock:
            # 记录事件历史
            self._event_history.append(event)
            if len(self._event_history) > self._max_history:
                self._event_history.pop(0)
            
            # 通知所有订阅者
            handlers = self._subscribers[event.type].copy()
        
        print(f"事件中介者: 发布事件 {event.type.value} from {event.source}")
        
        for handler in handlers:
            try:
                handler(event)
            except Exception as e:
                print(f"事件处理器执行失败: {e}")
    
    def get_event_history(self, event_type: EventType = None, limit: int = 10) -> List[Event]:
        """获取事件历史"""
        with self._lock:
            if event_type:
                filtered_events = [e for e in self._event_history if e.type == event_type]
                return filtered_events[-limit:]
            return self._event_history[-limit:]
    
    def get_subscriber_count(self, event_type: EventType) -> int:
        """获取订阅者数量"""
        return len(self._subscribers[event_type])


class EventDrivenComponent:
    """
    事件驱动的组件基类
    """
    
    def __init__(self, name: str, mediator: EventMediator):
        self.name = name
        self.mediator = mediator
        self._setup_event_handlers()
    
    def _setup_event_handlers(self) -> None:
        """设置事件处理器（子类重写）"""
        pass
    
    def publish_event(self, event_type: EventType, data: Dict[str, Any]) -> None:
        """发布事件"""
        event = Event(event_type, self.name, data)
        self.mediator.publish(event)


class UserManager(EventDrivenComponent):
    """
    用户管理器
    """
    
    def __init__(self, mediator: EventMediator):
        self.online_users: Set[str] = set()
        super().__init__("UserManager", mediator)
    
    def _setup_event_handlers(self) -> None:
        """设置事件处理器"""
        self.mediator.subscribe(EventType.USER_LOGIN, self._handle_user_login)
        self.mediator.subscribe(EventType.USER_LOGOUT, self._handle_user_logout)
    
    def _handle_user_login(self, event: Event) -> None:
        """处理用户登录事件"""
        username = event.data.get('username')
        if username:
            self.online_users.add(username)
            print(f"用户管理器: {username} 已登录，当前在线用户数: {len(self.online_users)}")
    
    def _handle_user_logout(self, event: Event) -> None:
        """处理用户登出事件"""
        username = event.data.get('username')
        if username:
            self.online_users.discard(username)
            print(f"用户管理器: {username} 已登出，当前在线用户数: {len(self.online_users)}")
    
    def get_online_users(self) -> List[str]:
        """获取在线用户列表"""
        return list(self.online_users)


class MessageLogger(EventDrivenComponent):
    """
    消息记录器
    """
    
    def __init__(self, mediator: EventMediator):
        self.message_log: List[Dict] = []
        super().__init__("MessageLogger", mediator)
    
    def _setup_event_handlers(self) -> None:
        """设置事件处理器"""
        self.mediator.subscribe(EventType.MESSAGE_SENT, self._handle_message_sent)
    
    def _handle_message_sent(self, event: Event) -> None:
        """处理消息发送事件"""
        log_entry = {
            'timestamp': event.timestamp,
            'sender': event.data.get('sender'),
            'recipient': event.data.get('recipient'),
            'message': event.data.get('message'),
            'message_type': event.data.get('message_type', 'text')
        }
        self.message_log.append(log_entry)
        print(f"消息记录器: 记录消息 - {log_entry['sender']} -> {log_entry['recipient']}")
    
    def get_message_log(self, limit: int = 10) -> List[Dict]:
        """获取消息日志"""
        return self.message_log[-limit:]
    
    def export_log(self, filename: str) -> None:
        """导出日志到文件"""
        try:
            with open(filename, 'w', encoding='utf-8') as f:
                json.dump(self.message_log, f, ensure_ascii=False, indent=2)
            print(f"消息记录器: 日志已导出到 {filename}")
        except Exception as e:
            print(f"消息记录器: 导出失败 - {e}")


class NotificationService(EventDrivenComponent):
    """
    通知服务
    """
    
    def __init__(self, mediator: EventMediator):
        self.notification_queue: List[Dict] = []
        super().__init__("NotificationService", mediator)
    
    def _setup_event_handlers(self) -> None:
        """设置事件处理器"""
        self.mediator.subscribe(EventType.USER_LOGIN, self._handle_user_login)
        self.mediator.subscribe(EventType.FILE_UPLOADED, self._handle_file_uploaded)
        self.mediator.subscribe(EventType.SYSTEM_NOTIFICATION, self._handle_system_notification)
    
    def _handle_user_login(self, event: Event) -> None:
        """处理用户登录通知"""
        username = event.data.get('username')
        notification = {
            'type': 'welcome',
            'recipient': username,
            'message': f"欢迎 {username}！",
            'timestamp': event.timestamp
        }
        self.notification_queue.append(notification)
        print(f"通知服务: 发送欢迎通知给 {username}")
    
    def _handle_file_uploaded(self, event: Event) -> None:
        """处理文件上传通知"""
        uploader = event.data.get('uploader')
        filename = event.data.get('filename')
        notification = {
            'type': 'file_upload',
            'recipient': 'all',
            'message': f"{uploader} 上传了文件: {filename}",
            'timestamp': event.timestamp
        }
        self.notification_queue.append(notification)
        print(f"通知服务: 广播文件上传通知 - {filename}")
    
    def _handle_system_notification(self, event: Event) -> None:
        """处理系统通知"""
        message = event.data.get('message')
        recipient = event.data.get('recipient', 'all')
        notification = {
            'type': 'system',
            'recipient': recipient,
            'message': message,
            'timestamp': event.timestamp
        }
        self.notification_queue.append(notification)
        print(f"通知服务: 系统通知 - {message}")
    
    def get_notifications(self, recipient: str = None, limit: int = 10) -> List[Dict]:
        """获取通知"""
        if recipient:
            filtered = [n for n in self.notification_queue 
                       if n['recipient'] in [recipient, 'all']]
            return filtered[-limit:]
        return self.notification_queue[-limit:]


# ============================================================================
# 3. 异步中介者模式
# ============================================================================

class AsyncMediator:
    """
    异步中介者
    支持异步事件处理
    """
    
    def __init__(self):
        self._handlers: Dict[str, List[Callable]] = defaultdict(list)
        self._event_queue: asyncio.Queue = asyncio.Queue()
        self._running = False
        self._worker_task = None
    
    async def start(self) -> None:
        """启动异步中介者"""
        if not self._running:
            self._running = True
            self._worker_task = asyncio.create_task(self._process_events())
            print("异步中介者: 已启动")
    
    async def stop(self) -> None:
        """停止异步中介者"""
        if self._running:
            self._running = False
            if self._worker_task:
                self._worker_task.cancel()
                try:
                    await self._worker_task
                except asyncio.CancelledError:
                    pass
            print("异步中介者: 已停止")
    
    def subscribe(self, event_type: str, handler: Callable) -> None:
        """订阅事件"""
        self._handlers[event_type].append(handler)
        print(f"异步中介者: 订阅事件 {event_type}")
    
    async def publish(self, event_type: str, data: Any, source: str = "unknown") -> None:
        """发布事件"""
        event = {
            'type': event_type,
            'data': data,
            'source': source,
            'timestamp': time.time()
        }
        await self._event_queue.put(event)
        print(f"异步中介者: 发布事件 {event_type} from {source}")
    
    async def _process_events(self) -> None:
        """处理事件队列"""
        while self._running:
            try:
                # 等待事件，超时1秒
                event = await asyncio.wait_for(self._event_queue.get(), timeout=1.0)
                await self._handle_event(event)
            except asyncio.TimeoutError:
                continue
            except Exception as e:
                print(f"异步中介者: 事件处理错误 - {e}")
    
    async def _handle_event(self, event: Dict) -> None:
        """处理单个事件"""
        event_type = event['type']
        handlers = self._handlers[event_type].copy()
        
        # 并发执行所有处理器
        tasks = []
        for handler in handlers:
            if asyncio.iscoroutinefunction(handler):
                tasks.append(asyncio.create_task(handler(event)))
            else:
                # 同步处理器在线程池中执行
                tasks.append(asyncio.create_task(
                    asyncio.get_event_loop().run_in_executor(None, handler, event)
                ))
        
        if tasks:
            await asyncio.gather(*tasks, return_exceptions=True)


class AsyncChatUser:
    """
    异步聊天用户
    """
    
    def __init__(self, name: str, mediator: AsyncMediator):
        self.name = name
        self.mediator = mediator
        self.messages: List[str] = []
        self._setup_handlers()
    
    def _setup_handlers(self) -> None:
        """设置事件处理器"""
        self.mediator.subscribe('message', self._handle_message)
        self.mediator.subscribe('user_joined', self._handle_user_joined)
        self.mediator.subscribe('user_left', self._handle_user_left)
    
    async def send_message(self, message: str, target: str = None) -> None:
        """发送消息"""
        await self.mediator.publish('message', {
            'sender': self.name,
            'message': message,
            'target': target
        }, self.name)
    
    async def join_chat(self) -> None:
        """加入聊天"""
        await self.mediator.publish('user_joined', {
            'username': self.name
        }, self.name)
    
    async def leave_chat(self) -> None:
        """离开聊天"""
        await self.mediator.publish('user_left', {
            'username': self.name
        }, self.name)
    
    async def _handle_message(self, event: Dict) -> None:
        """处理消息事件"""
        data = event['data']
        sender = data['sender']
        message = data['message']
        target = data.get('target')
        
        # 如果是私聊且不是发给自己的，忽略
        if target and target != self.name:
            return
        
        # 不接收自己发送的消息
        if sender == self.name:
            return
        
        formatted_message = f"[{sender}]: {message}"
        self.messages.append(formatted_message)
        print(f"{self.name} 收到消息: {formatted_message}")
    
    async def _handle_user_joined(self, event: Dict) -> None:
        """处理用户加入事件"""
        username = event['data']['username']
        if username != self.name:
            print(f"{self.name} 看到: {username} 加入了聊天")
    
    async def _handle_user_left(self, event: Dict) -> None:
        """处理用户离开事件"""
        username = event['data']['username']
        if username != self.name:
            print(f"{self.name} 看到: {username} 离开了聊天")
    
    def get_messages(self) -> List[str]:
        """获取消息历史"""
        return self.messages.copy()


# ============================================================================
# 4. 智能家居系统示例（实际应用）
# ============================================================================

class DeviceType(Enum):
    """设备类型"""
    LIGHT = "light"
    THERMOSTAT = "thermostat"
    SECURITY_CAMERA = "security_camera"
    DOOR_LOCK = "door_lock"
    SENSOR = "sensor"


class SmartDevice(ABC):
    """
    智能设备抽象基类
    """
    
    def __init__(self, device_id: str, device_type: DeviceType, room: str):
        self.device_id = device_id
        self.device_type = device_type
        self.room = room
        self.is_online = False
        self.mediator: Optional['SmartHomeMediator'] = None
    
    def set_mediator(self, mediator: 'SmartHomeMediator') -> None:
        """设置中介者"""
        self.mediator = mediator
    
    def notify_mediator(self, event: str, data: Dict[str, Any]) -> None:
        """通知中介者"""
        if self.mediator:
            self.mediator.handle_device_event(self, event, data)
    
    @abstractmethod
    def execute_command(self, command: str, params: Dict[str, Any]) -> bool:
        """执行命令"""
        pass
    
    def get_status(self) -> Dict[str, Any]:
        """获取设备状态"""
        return {
            'device_id': self.device_id,
            'device_type': self.device_type.value,
            'room': self.room,
            'is_online': self.is_online
        }


class SmartLight(SmartDevice):
    """
    智能灯泡
    """
    
    def __init__(self, device_id: str, room: str):
        super().__init__(device_id, DeviceType.LIGHT, room)
        self.is_on = False
        self.brightness = 100
        self.color = "white"
    
    def execute_command(self, command: str, params: Dict[str, Any]) -> bool:
        """执行命令"""
        try:
            if command == "turn_on":
                self.is_on = True
                print(f"智能灯 {self.device_id}: 已开启")
            elif command == "turn_off":
                self.is_on = False
                print(f"智能灯 {self.device_id}: 已关闭")
            elif command == "set_brightness":
                self.brightness = max(0, min(100, params.get('brightness', 100)))
                print(f"智能灯 {self.device_id}: 亮度设置为 {self.brightness}%")
            elif command == "set_color":
                self.color = params.get('color', 'white')
                print(f"智能灯 {self.device_id}: 颜色设置为 {self.color}")
            else:
                return False
            
            # 通知状态变化
            self.notify_mediator('status_changed', self.get_status())
            return True
        except Exception as e:
            print(f"智能灯 {self.device_id}: 命令执行失败 - {e}")
            return False
    
    def get_status(self) -> Dict[str, Any]:
        """获取设备状态"""
        status = super().get_status()
        status.update({
            'is_on': self.is_on,
            'brightness': self.brightness,
            'color': self.color
        })
        return status


class SmartThermostat(SmartDevice):
    """
    智能温控器
    """
    
    def __init__(self, device_id: str, room: str):
        super().__init__(device_id, DeviceType.THERMOSTAT, room)
        self.target_temperature = 22.0
        self.current_temperature = 20.0
        self.mode = "auto"  # auto, heat, cool, off
    
    def execute_command(self, command: str, params: Dict[str, Any]) -> bool:
        """执行命令"""
        try:
            if command == "set_temperature":
                self.target_temperature = params.get('temperature', 22.0)
                print(f"温控器 {self.device_id}: 目标温度设置为 {self.target_temperature}°C")
            elif command == "set_mode":
                self.mode = params.get('mode', 'auto')
                print(f"温控器 {self.device_id}: 模式设置为 {self.mode}")
            elif command == "update_current_temperature":
                old_temp = self.current_temperature
                self.current_temperature = params.get('temperature', self.current_temperature)
                print(f"温控器 {self.device_id}: 当前温度 {self.current_temperature}°C")
                
                # 如果温度变化较大，触发警报
                if abs(self.current_temperature - old_temp) > 5:
                    self.notify_mediator('temperature_alert', {
                        'device_id': self.device_id,
                        'old_temperature': old_temp,
                        'new_temperature': self.current_temperature
                    })
            else:
                return False
            
            self.notify_mediator('status_changed', self.get_status())
            return True
        except Exception as e:
            print(f"温控器 {self.device_id}: 命令执行失败 - {e}")
            return False
    
    def get_status(self) -> Dict[str, Any]:
        """获取设备状态"""
        status = super().get_status()
        status.update({
            'target_temperature': self.target_temperature,
            'current_temperature': self.current_temperature,
            'mode': self.mode
        })
        return status


class MotionSensor(SmartDevice):
    """
    运动传感器
    """
    
    def __init__(self, device_id: str, room: str):
        super().__init__(device_id, DeviceType.SENSOR, room)
        self.motion_detected = False
        self.last_motion_time = None
    
    def execute_command(self, command: str, params: Dict[str, Any]) -> bool:
        """执行命令"""
        try:
            if command == "detect_motion":
                self.motion_detected = True
                self.last_motion_time = time.time()
                print(f"运动传感器 {self.device_id}: 检测到运动")
                
                # 通知运动检测事件
                self.notify_mediator('motion_detected', {
                    'device_id': self.device_id,
                    'room': self.room,
                    'timestamp': self.last_motion_time
                })
            elif command == "clear_motion":
                self.motion_detected = False
                print(f"运动传感器 {self.device_id}: 运动状态清除")
            else:
                return False
            
            self.notify_mediator('status_changed', self.get_status())
            return True
        except Exception as e:
            print(f"运动传感器 {self.device_id}: 命令执行失败 - {e}")
            return False
    
    def get_status(self) -> Dict[str, Any]:
        """获取设备状态"""
        status = super().get_status()
        status.update({
            'motion_detected': self.motion_detected,
            'last_motion_time': self.last_motion_time
        })
        return status


class SmartHomeMediator:
    """
    智能家居中介者
    协调各种智能设备之间的交互
    """
    
    def __init__(self, home_name: str):
        self.home_name = home_name
        self.devices: Dict[str, SmartDevice] = {}
        self.automation_rules: List[Dict] = []
        self.event_log: List[Dict] = []
        self.security_mode = False
    
    def add_device(self, device: SmartDevice) -> None:
        """添加设备"""
        self.devices[device.device_id] = device
        device.set_mediator(self)
        device.is_online = True
        print(f"智能家居 {self.home_name}: 添加设备 {device.device_id} ({device.device_type.value})")
    
    def remove_device(self, device_id: str) -> None:
        """移除设备"""
        if device_id in self.devices:
            device = self.devices[device_id]
            device.is_online = False
            device.set_mediator(None)
            del self.devices[device_id]
            print(f"智能家居 {self.home_name}: 移除设备 {device_id}")
    
    def handle_device_event(self, device: SmartDevice, event: str, data: Dict[str, Any]) -> None:
        """处理设备事件"""
        # 记录事件
        event_record = {
            'timestamp': time.time(),
            'device_id': device.device_id,
            'event': event,
            'data': data
        }
        self.event_log.append(event_record)
        
        print(f"智能家居中介者: 处理事件 {event} from {device.device_id}")
        
        # 处理特定事件
        if event == 'motion_detected':
            self._handle_motion_detected(device, data)
        elif event == 'temperature_alert':
            self._handle_temperature_alert(device, data)
        elif event == 'status_changed':
            self._handle_status_changed(device, data)
        
        # 执行自动化规则
        self._execute_automation_rules(event, device, data)
    
    def _handle_motion_detected(self, device: SmartDevice, data: Dict[str, Any]) -> None:
        """处理运动检测事件"""
        room = data['room']
        
        # 如果是安全模式，触发警报
        if self.security_mode:
            print(f"智能家居: 安全警报！{room} 检测到运动")
            return
        
        # 自动开启房间灯光
        for device_id, device in self.devices.items():
            if (isinstance(device, SmartLight) and 
                device.room == room and 
                not device.is_on):
                device.execute_command('turn_on', {})
                print(f"智能家居: 自动开启 {room} 的灯光")
    
    def _handle_temperature_alert(self, device: SmartDevice, data: Dict[str, Any]) -> None:
        """处理温度警报事件"""
        old_temp = data['old_temperature']
        new_temp = data['new_temperature']
        print(f"智能家居: 温度异常警报！从 {old_temp}°C 变为 {new_temp}°C")
    
    def _handle_status_changed(self, device: SmartDevice, data: Dict[str, Any]) -> None:
        """处理状态变化事件"""
        # 可以在这里实现状态同步逻辑
        pass
    
    def _execute_automation_rules(self, event: str, device: SmartDevice, data: Dict[str, Any]) -> None:
        """执行自动化规则"""
        for rule in self.automation_rules:
            try:
                if self._match_rule_condition(rule, event, device, data):
                    self._execute_rule_action(rule)
            except Exception as e:
                print(f"自动化规则执行失败: {e}")
    
    def _match_rule_condition(self, rule: Dict, event: str, device: SmartDevice, data: Dict[str, Any]) -> bool:
        """匹配规则条件"""
        condition = rule.get('condition', {})
        
        # 检查事件类型
        if condition.get('event') and condition['event'] != event:
            return False
        
        # 检查设备类型
        if condition.get('device_type') and condition['device_type'] != device.device_type.value:
            return False
        
        # 检查房间
        if condition.get('room') and condition['room'] != device.room:
            return False
        
        return True
    
    def _execute_rule_action(self, rule: Dict) -> None:
        """执行规则动作"""
        action = rule.get('action', {})
        target_devices = action.get('target_devices', [])
        command = action.get('command')
        params = action.get('params', {})
        
        for device_id in target_devices:
            if device_id in self.devices:
                device = self.devices[device_id]
                device.execute_command(command, params)
                print(f"自动化规则: 对设备 {device_id} 执行命令 {command}")
    
    def add_automation_rule(self, rule: Dict) -> None:
        """添加自动化规则"""
        self.automation_rules.append(rule)
        print(f"智能家居: 添加自动化规则 - {rule.get('name', '未命名')}")
    
    def set_security_mode(self, enabled: bool) -> None:
        """设置安全模式"""
        self.security_mode = enabled
        mode_text = "启用" if enabled else "禁用"
        print(f"智能家居: {mode_text}安全模式")
    
    def execute_scene(self, scene_name: str) -> None:
        """执行场景"""
        scenes = {
            'good_morning': {
                'description': '早安场景',
                'actions': [
                    {'device_type': 'light', 'command': 'turn_on', 'params': {'brightness': 80}},
                    {'device_type': 'thermostat', 'command': 'set_temperature', 'params': {'temperature': 23}}
                ]
            },
            'good_night': {
                'description': '晚安场景',
                'actions': [
                    {'device_type': 'light', 'command': 'turn_off', 'params': {}},
                    {'device_type': 'thermostat', 'command': 'set_temperature', 'params': {'temperature': 20}}
                ]
            },
            'away': {
                'description': '离家场景',
                'actions': [
                    {'device_type': 'light', 'command': 'turn_off', 'params': {}},
                    {'device_type': 'thermostat', 'command': 'set_mode', 'params': {'mode': 'off'}}
                ]
            }
        }
        
        if scene_name in scenes:
            scene = scenes[scene_name]
            print(f"智能家居: 执行场景 '{scene['description']}'")
            
            for action in scene['actions']:
                device_type = action['device_type']
                command = action['command']
                params = action['params']
                
                for device in self.devices.values():
                    if device.device_type.value == device_type:
                        device.execute_command(command, params)
        else:
            print(f"智能家居: 未知场景 '{scene_name}'")
    
    def get_system_status(self) -> Dict[str, Any]:
        """获取系统状态"""
        device_status = {}
        for device_id, device in self.devices.items():
            device_status[device_id] = device.get_status()
        
        return {
            'home_name': self.home_name,
            'security_mode': self.security_mode,
            'device_count': len(self.devices),
            'online_devices': sum(1 for d in self.devices.values() if d.is_online),
            'devices': device_status,
            'automation_rules_count': len(self.automation_rules)
        }
    
    def get_event_log(self, limit: int = 10) -> List[Dict]:
        """获取事件日志"""
        return self.event_log[-limit:]


# ============================================================================
# 5. 演示函数
# ============================================================================

def demonstrate_traditional_mediator():
    """
    演示传统中介者模式
    """
    print("\n=== 传统中介者模式演示 ===")
    
    # 创建聊天室
    chat_room = ChatRoom("技术讨论群")
    
    # 创建用户
    alice = ChatUser("Alice")
    bob = ChatUser("Bob")
    charlie = ChatUser("Charlie")
    
    # 添加用户到聊天室
    chat_room.add_user(alice)
    chat_room.add_user(bob)
    chat_room.add_user(charlie)
    
    print(f"\n在线用户: {chat_room.get_online_users()}")
    
    # 用户交互
    print("\n=== 用户交互 ===")
    alice.send_message("大家好！")
    bob.send_message("你好 Alice！")
    charlie.send_message("欢迎加入讨论！")
    
    # 私聊
    print("\n=== 私聊消息 ===")
    alice.send_message("Bob，你在做什么项目？", "Bob")
    bob.send_message("我在学习Python设计模式", "Alice")
    
    # 房间功能
    print("\n=== 房间功能 ===")
    alice.join_room("Python学习")
    bob.join_room("Python学习")
    
    print(f"Python学习房间用户: {chat_room.get_room_users('Python学习')}")
    
    chat_room.broadcast_to_room("Python学习", "欢迎来到Python学习房间！")
    
    # 显示消息历史
    print("\n=== 消息历史 ===")
    for record in chat_room.get_message_history():
        timestamp = time.strftime('%H:%M:%S', time.localtime(record['timestamp']))
        print(f"[{timestamp}] {record['sender']}: {record['message']}")


def demonstrate_event_driven_mediator():
    """
    演示事件驱动的中介者模式
    """
    print("\n=== 事件驱动中介者模式演示 ===")
    
    # 创建事件中介者
    mediator = EventMediator()
    
    # 创建组件
    user_manager = UserManager(mediator)
    message_logger = MessageLogger(mediator)
    notification_service = NotificationService(mediator)
    
    print("\n=== 用户登录/登出 ===")
    # 模拟用户登录
    mediator.publish(Event(EventType.USER_LOGIN, "system", {'username': 'alice'}))
    mediator.publish(Event(EventType.USER_LOGIN, "system", {'username': 'bob'}))
    
    print(f"在线用户: {user_manager.get_online_users()}")
    
    # 模拟消息发送
    print("\n=== 消息发送 ===")
    mediator.publish(Event(EventType.MESSAGE_SENT, "alice", {
        'sender': 'alice',
        'recipient': 'bob',
        'message': '你好 Bob！',
        'message_type': 'text'
    }))
    
    mediator.publish(Event(EventType.MESSAGE_SENT, "bob", {
        'sender': 'bob',
        'recipient': 'alice',
        'message': '你好 Alice！',
        'message_type': 'text'
    }))
    
    # 模拟文件上传
    print("\n=== 文件上传 ===")
    mediator.publish(Event(EventType.FILE_UPLOADED, "alice", {
        'uploader': 'alice',
        'filename': 'document.pdf',
        'file_size': 1024000
    }))
    
    # 系统通知
    print("\n=== 系统通知 ===")
    mediator.publish(Event(EventType.SYSTEM_NOTIFICATION, "system", {
        'message': '系统将在10分钟后维护',
        'recipient': 'all'
    }))
    
    # 用户登出
    print("\n=== 用户登出 ===")
    mediator.publish(Event(EventType.USER_LOGOUT, "system", {'username': 'bob'}))
    
    print(f"在线用户: {user_manager.get_online_users()}")
    
    # 显示日志和通知
    print("\n=== 消息日志 ===")
    for log_entry in message_logger.get_message_log():
        timestamp = time.strftime('%H:%M:%S', time.localtime(log_entry['timestamp']))
        print(f"[{timestamp}] {log_entry['sender']} -> {log_entry['recipient']}: {log_entry['message']}")
    
    print("\n=== 通知列表 ===")
    for notification in notification_service.get_notifications():
        timestamp = time.strftime('%H:%M:%S', time.localtime(notification['timestamp']))
        print(f"[{timestamp}] {notification['type']}: {notification['message']}")


async def demonstrate_async_mediator():
    """
    演示异步中介者模式
    """
    print("\n=== 异步中介者模式演示 ===")
    
    # 创建异步中介者
    mediator = AsyncMediator()
    await mediator.start()
    
    # 创建异步聊天用户
    alice = AsyncChatUser("Alice", mediator)
    bob = AsyncChatUser("Bob", mediator)
    charlie = AsyncChatUser("Charlie", mediator)
    
    # 用户加入聊天
    print("\n=== 用户加入聊天 ===")
    await alice.join_chat()
    await bob.join_chat()
    await charlie.join_chat()
    
    # 等待事件处理
    await asyncio.sleep(0.1)
    
    # 发送消息
    print("\n=== 发送消息 ===")
    await alice.send_message("大家好！")
    await bob.send_message("你好 Alice！")
    await charlie.send_message("欢迎！")
    
    # 私聊
    print("\n=== 私聊消息 ===")
    await alice.send_message("Bob，你在吗？", "Bob")
    await bob.send_message("我在，有什么事吗？", "Alice")
    
    # 等待所有消息处理完成
    await asyncio.sleep(0.2)
    
    # 用户离开
    print("\n=== 用户离开 ===")
    await charlie.leave_chat()
    
    await asyncio.sleep(0.1)
    
    # 显示消息历史
    print("\n=== 消息历史 ===")
    print(f"Alice的消息: {alice.get_messages()}")
    print(f"Bob的消息: {bob.get_messages()}")
    print(f"Charlie的消息: {charlie.get_messages()}")
    
    # 停止中介者
    await mediator.stop()


def demonstrate_smart_home_system():
    """
    演示智能家居系统
    """
    print("\n=== 智能家居系统演示 ===")
    
    # 创建智能家居中介者
    smart_home = SmartHomeMediator("我的智能家居")
    
    # 创建设备
    living_room_light = SmartLight("light_001", "客厅")
    bedroom_light = SmartLight("light_002", "卧室")
    thermostat = SmartThermostat("thermo_001", "客厅")
    motion_sensor = MotionSensor("sensor_001", "客厅")
    
    # 添加设备到系统
    smart_home.add_device(living_room_light)
    smart_home.add_device(bedroom_light)
    smart_home.add_device(thermostat)
    smart_home.add_device(motion_sensor)
    
    # 添加自动化规则
    print("\n=== 添加自动化规则 ===")
    
    # 规则1：运动检测时自动开灯
    motion_rule = {
        'name': '运动检测开灯',
        'condition': {
            'event': 'motion_detected',
            'device_type': 'sensor'
        },
        'action': {
            'target_devices': ['light_001'],
            'command': 'turn_on',
            'params': {'brightness': 70}
        }
    }
    smart_home.add_automation_rule(motion_rule)
    
    # 设备操作
    print("\n=== 设备操作 ===")
    living_room_light.execute_command('turn_on', {})
    living_room_light.execute_command('set_brightness', {'brightness': 80})
    living_room_light.execute_command('set_color', {'color': 'warm_white'})
    
    thermostat.execute_command('set_temperature', {'temperature': 24})
    thermostat.execute_command('update_current_temperature', {'temperature': 22})
    
    # 触发运动检测
    print("\n=== 触发运动检测 ===")
    motion_sensor.execute_command('detect_motion', {})
    
    # 场景执行
    print("\n=== 场景执行 ===")
    smart_home.execute_scene('good_morning')
    
    time.sleep(1)
    
    smart_home.execute_scene('good_night')
    
    # 安全模式测试
    print("\n=== 安全模式测试 ===")
    smart_home.set_security_mode(True)
    motion_sensor.execute_command('detect_motion', {})
    
    # 显示系统状态
    print("\n=== 系统状态 ===")
    status = smart_home.get_system_status()
    print(f"家居名称: {status['home_name']}")
    print(f"安全模式: {status['security_mode']}")
    print(f"设备总数: {status['device_count']}")
    print(f"在线设备: {status['online_devices']}")
    
    print("\n设备详情:")
    for device_id, device_status in status['devices'].items():
        print(f"  {device_id}: {device_status}")
    
    # 显示事件日志
    print("\n=== 事件日志 ===")
    for event in smart_home.get_event_log():
        timestamp = time.strftime('%H:%M:%S', time.localtime(event['timestamp']))
        print(f"[{timestamp}] {event['device_id']}: {event['event']}")


def demonstrate_performance_comparison():
    """
    演示性能对比
    """
    print("\n=== 性能对比演示 ===")
    
    # 创建大量用户进行性能测试
    print("\n=== 传统中介者性能测试 ===")
    
    start_time = time.time()
    
    # 创建聊天室和大量用户
    chat_room = ChatRoom("性能测试群")
    users = []
    
    for i in range(100):
        user = ChatUser(f"User{i}")
        users.append(user)
        chat_room.add_user(user)
    
    # 发送大量消息
    for i in range(50):
        user = users[i % len(users)]
        user.send_message(f"测试消息 {i}")
    
    traditional_time = time.time() - start_time
    print(f"传统中介者处理时间: {traditional_time:.3f}秒")
    
    # 事件驱动中介者性能测试
    print("\n=== 事件驱动中介者性能测试 ===")
    
    start_time = time.time()
    
    mediator = EventMediator()
    message_logger = MessageLogger(mediator)
    
    # 发送大量事件
    for i in range(100):
        mediator.publish(Event(EventType.MESSAGE_SENT, f"user{i}", {
            'sender': f'user{i}',
            'recipient': 'all',
            'message': f'测试消息 {i}',
            'message_type': 'text'
        }))
    
    event_driven_time = time.time() - start_time
    print(f"事件驱动中介者处理时间: {event_driven_time:.3f}秒")
    
    # 性能对比总结
    print(f"\n=== 性能对比总结 ===")
    print(f"传统中介者: {traditional_time:.3f}秒")
    print(f"事件驱动中介者: {event_driven_time:.3f}秒")
    
    if traditional_time < event_driven_time:
        print(f"传统中介者更快 ({event_driven_time/traditional_time:.2f}x)")
    else:
        print(f"事件驱动中介者更快 ({traditional_time/event_driven_time:.2f}x)")


def demonstrate_java_comparison():
    """
    演示与Java的对比
    """
    print("\n=== Python vs Java 中介者模式对比 ===")
    
    print("\n=== Java实现特点 ===")
    print("""
    Java中介者模式的实现:
    
    // Java Mediator接口
    public interface Mediator {
        void notify(Component sender, String event);
    }
    
    // Java Component抽象类
    public abstract class Component {
        protected Mediator mediator;
        
        public Component(Mediator mediator) {
            this.mediator = mediator;
        }
        
        public void setMediator(Mediator mediator) {
            this.mediator = mediator;
        }
    }
    
    // Java具体中介者
    public class ConcreteMediator implements Mediator {
        private List<Component> components = new ArrayList<>();
        
        @Override
        public void notify(Component sender, String event) {
            // 处理组件间的交互逻辑
        }
    }
    """)
    
    print("\n=== Python实现优势 ===")
    print("""
    Python中介者模式的优势:
    
    1. 动态特性:
       - 可以动态添加和移除事件处理器
       - 支持运行时修改中介者行为
    
    2. 函数式编程支持:
       - 可以使用函数作为事件处理器
       - 支持lambda表达式和闭包
    
    3. 装饰器简化:
       - 使用装饰器简化事件订阅
       - 减少样板代码
    
    4. 异步支持:
       - 原生支持异步事件处理
       - 适合高并发场景
    
    5. 弱引用支持:
       - 避免循环引用问题
       - 自动内存管理
    """)
    
    print("\n=== 实际应用场景对比 ===")
    print("""
    应用场景对比:
    
    Java适合:
    - 大型企业级应用
    - 严格的类型安全要求
    - 复杂的业务逻辑
    
    Python适合:
    - 快速原型开发
    - 数据处理和分析
    - 微服务架构
    - 异步IO密集型应用
    """)


def main():
    """
    主函数：演示所有中介者模式实现
    """
    print("中介者模式 (Mediator Pattern) - Python实现详解")
    print("=" * 60)
    
    # 演示传统中介者模式
    demonstrate_traditional_mediator()
    
    # 演示事件驱动中介者模式
    demonstrate_event_driven_mediator()
    
    # 演示异步中介者模式
    print("\n=== 异步中介者模式演示 ===")
    asyncio.run(demonstrate_async_mediator())
    
    # 演示智能家居系统
    demonstrate_smart_home_system()
    
    # 性能对比
    demonstrate_performance_comparison()
    
    # Java对比
    demonstrate_java_comparison()
    
    print("\n=== 总结 ===")
    print("""
    中介者模式的核心价值:
    
    1. 降低耦合度:
       - 对象之间不直接通信
       - 通过中介者协调交互
    
    2. 集中控制:
       - 交互逻辑集中在中介者中
       - 便于维护和扩展
    
    3. 可复用性:
       - 中介者可以被多个对象复用
       - 支持不同的交互模式
    
    4. Python特有优势:
       - 动态特性提供更大灵活性
       - 函数式编程简化实现
       - 异步支持适合现代应用
       - 装饰器减少样板代码
    
    适用场景:
    - GUI应用程序
    - 聊天系统
    - 工作流引擎
    - 智能家居系统
    - 微服务通信
    - 事件驱动架构
    """)


if __name__ == "__main__":
    main()